package parser

import (
	"fetcher/crawler/engine"
	"fetcher/crawler/model"
	"regexp"
	"strconv"
)

//var ageRegex = regexp.MustCompile(`<div data-v-8b1eac0c="" class="m-btn purple">([/d]+)岁</div>`)
var ageRegex = regexp.MustCompile(`<div class="m-btn purple" [^>]*>([\d]+)岁</div>`)
var marriageRegex = regexp.MustCompile(`<div class="m-btn purple" [^>]*>([^<]+)</div>`)
var incomeRegex = regexp.MustCompile(`<div class="m-btn purple" [^>]*>月收入:([^<]+)</div>`)
var heightRegex = regexp.MustCompile(`<div class="m-btn purple" [^>]*>([\d]+)cm</div>`)
var weightRegex = regexp.MustCompile(`<div class="m-btn purple" [^>]*>([\d]+)kg</div>`)

func ParseProfile(contents []byte, name string) engine.ParseResult {
	profile := model.Profile{}
	ageInfo := extractString(contents, ageRegex)
	age := 0
	if len(ageInfo) > 0 {
		age, _ = strconv.Atoi(ageInfo)
	}
	profile.Name = name
	profile.Age = age
	profile.Marriage = extractString(contents, marriageRegex)
	profile.Income = extractString(contents, incomeRegex)
	heightInfo := extractString(contents, heightRegex)
	height := 0
	if len(heightInfo) > 0 {
		height, _ = strconv.Atoi(heightInfo)
	}
	profile.Height = height
	weight := 0
	weightInfo := extractString(contents, weightRegex)
	if len(weightInfo) > 0 {
		weight, _ = strconv.Atoi(weightInfo)
	}
	profile.Weight = weight
	return engine.ParseResult{
		Items: []interface{}{profile},
	}
}

func extractString(contents []byte, re *regexp.Regexp) string {
	match := re.FindSubmatch(contents)
	if len(match) >= 2 {
		return string(match[1])
	} else {
		return ""
	}
}
